<?php

namespace app\api\controller;

use think\Db;

use app\common\controller\UnLogin;
use app\common\service\TranslateService;

class Redpacket extends UnLogin{

	public $uid;
    public $user_info;

	public function bindAccount(){
		$account  = P('account');
		$password = P('password');

		if (empty($account)) {
			$this->retData(1, '缺少参数账户(account)');
		}
		if (empty($password)) {
			$this->retData(1, '缺少参数登录密码(password)');
		}
		$user_info = model('UserModel')->infoByPhone($account);

		if (empty($user_info)) {
			$this->retData(1, '用户不存在');
		}
		if ($user_info['status'] == 0) {
			$this->retData(1, '账号已被冻结，禁止登录');
		}
		if (md5($password) != $user_info['password']) {
			$this->retData(1, '登录密码错误');
		}
		$data['uid'] = $user_info['id'];
		$data['username'] = $user_info['username'];
		$token = model('TokenModel2')->setToken($data['uid']);
		// model('CaptchaModel')->delCaptcha($captcha['id']);
		if (!$token) {
			$this->retData(1, '绑定失败');
		} else {
			$data['token'] = $token;
			$this->retData(0, '绑定成功', $data);
		}
	}

	public function redpacket(){
		$uid   = P('uid');
        $token = P('token');
        $code  = P('code');
        if (empty($uid) || empty($token) || empty($code)) {
            $this->retData(1,'缺少参数');
        }
        $check_token = model('TokenModel2')->veriToken($uid, $token);
        if(empty($check_token)){
            $this->retData(-1,'没有绑定账号');
        }
        
        Db::startTrans();
        $list = Db::table('tp_invest_code2')->where('code',$code)->where('status',1)->lock(true)->select();
        if (empty($list)) {
        	$this->retData(1,'红包已抢完');
        } 
        $has = Db::table('tp_invest_code2')->where('code',$code)->where('uid',$uid)->find();
        if ($has) {
        	$this->retData(0,'success',['hb_code'=>$has['hb_code'],'amount'=>$has['amount']]);
        }
        $ids = array_column($list, 'id');
        $id  = array_rand($ids);
        $id  = $ids[$id];
        $info = Db::table('tp_invest_code2')->where('id',$id)->lock(true)->find();
        if ($info['status'] != 1 || $info['uid'] != 0) {
        	$this->retData(1,'系统出错1');
        }

        $res = Db::table('tp_invest_code2')->where('id',$id)->update([
        	'status'=>2,
        	'uid'=>$uid,
        ]);
        if ($res) {
        	Db::commit();
        	$this->retData(0,'success',['hb_code'=>$info['hb_code'],'amount'=>$info['amount']]);
        } else {
        	Db::rollback();
        	$this->retData(1,'系统出错2');
        }
	}

}